package com.nox.trademe.testapp.fragments;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.nox.trademe.testapp.R;
import com.nox.trademe.testapp.adapters.CustomItemListAdapter;
import com.nox.trademe.testapp.models.Item;
import com.nox.trademe.testapp.utils.KeyContainer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ListItemFragment extends Fragment {
    public static final String TAG = "ListItemFragment";
    private ArrayList<Item> items = new ArrayList<Item>();
    private ListView itemListView;
    private CustomItemListAdapter adapter;
    private String category;

    public ListItemFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.v(TAG, "Activity State: onCreateView()");
        View view = inflater.inflate(R.layout.fragment_itemlist, container, false);

        Bundle args = getArguments();
        if (args == null) {
            category = null;
            Log.v(TAG, "Category NOT received in bundle");
            return view;
        }

        category = (String)args.getString(KeyContainer.listingItemViewBundle);
        Log.v(TAG, "Category received in bundle");

        itemListView = (ListView) view.findViewById(R.id.itemList);

        adapter = new CustomItemListAdapter(items,	getActivity());
        itemListView.setAdapter(adapter);
//        categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//                ((CategoryListener) getActivity()).onChangeCategory(categoryList.get(position), true);
//            }
//        });
//        setHasOptionsMenu(false);
//
        (new AsyncListViewLoader()).execute("http://api.trademe.co.nz/v1/Search/General.json?category="+category);
        Log.v(TAG, "Activity State: onCreateView() finished");
        return view;
    }

    private class AsyncListViewLoader extends AsyncTask<String, Void, List<Item>> {
        public static final String TAG = "AsyncListViewLoader";
        private final CustomProgressDialogFragment dialog;

        private AsyncListViewLoader() {
            dialog = new CustomProgressDialogFragment();
        }

        @Override
        protected void onPostExecute(List<Item> result) {
            Log.v(TAG, "Activity State: onPostExecute()");
            super.onPostExecute(result);
            dialog.dismiss();
            adapter.notifyDataSetChanged();
        }

        @Override
        protected void onPreExecute() {
            Log.v(TAG, "Activity State: onPreExecute()");

            super.onPreExecute();
            dialog.show(getActivity().getSupportFragmentManager(), TAG);
        }

        @Override
        protected List<Item> doInBackground(String... params) {

            Log.v(TAG, "Activity State: doInBackground()");
            items.clear();
            try {
                URL u = new URL(params[0]);

                HttpURLConnection connection = (HttpURLConnection) u
                        .openConnection();
                connection.setRequestMethod("GET");

                connection.connect();
                int statusCode = connection.getResponseCode();
                if (statusCode != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Invalid Response Code: " + statusCode);
                    Log.e(TAG,
                            "GET Response Message: "
                                    + connection.getResponseMessage());
                    return items;
                } else {
                    Log.v(TAG, "Items Listing received");
                    Log.d(TAG, "GET Response Message: " + connection.getResponseMessage());
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    br.close();
                    try {
                        Log.d(TAG, "Response stream: " + sb.toString());
                        JSONObject response = new JSONObject(sb.toString());
                        //Log.d(TAG, "Response stream: " + response.toString());
                        JSONArray itemsArray = response.getJSONArray("List");
                        //Log.d(TAG, "Categories stream: " + mainCategoriesArray.toString());
                        for (int i = 0; i < itemsArray.length(); i++) {
                            //Log.d(TAG, "Adding Category from stream : " + mainCategoriesArray.getJSONObject(i).toString());
                            items.add(convertJSONObjectToItem(itemsArray.getJSONObject(i)));
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "Failed to parse JSON.", e);
                    }
                }
                connection.disconnect();
            } catch (Throwable t) {
                t.printStackTrace();
            }
            return items;
        }

        private Item convertJSONObjectToItem(JSONObject obj) throws JSONException {

            String itemID = obj.getString("ListingId");
            String name = obj.getString("Title");
            String categoryNumber = "";
            String picture = "";
            String price = "";
            return new Item(itemID, name, categoryNumber, picture, price);
        }
    }

}
